import Vue from 'vue'
import router from './router'
import store from './store'

import NProgress from 'nprogress' ;
import 'nprogress/nprogress.css' ;
import { constantRouterMap } from '@/config/router.config';
import {
    getState,
    getQueryVariable,
    MS_,
    client_id,
    getAuthorizeUri
} from "@public/public";
import rxAjax from '@/assets/js/ajax.js';
import {JsConstant,TokenUtil,MessageBox,I18Parse} from '@lowcode/jpaas-common-lib';
import componentLang from "@/locales/lang/impl/layouts/compomentLang";

NProgress.configure({showSpinner: false})
//不需要登录访问的白名单路由名称集合。
const whiteList = ['login', 'register', 'registerResult', 'forget', 'Signature',
    'singlelogin', 'tenantLogin','qrcodeLogin','ticketLogin','mobileCodeLogin'];

function hasRouter(obj,url,callback){
    let flag = callback(obj,url);
    if(flag){
        return true;
    }
    if(obj.children && obj.children.length>0){
        for(let i=0;i<obj.children.length;i++){
            let path = obj.children[i].path;
            path = (path.indexOf("/")==0?'':'/') + path;
            flag = hasRouter(obj.children[i],url + path,callback);
            if(flag){
                return true;
            }
        }
    }
    return false;
}

router.beforeEach((to, from, next) => {
    NProgress.start();
    store.state.appSetting.loading = true
    if(to.query){
        store.state.appSetting.hideArea = to.query.hide=='yes' ? true:false;
    }
    let _token =  TokenUtil.getToken();
    if (_token) {
        /* has token */
        if (to.path === '/user/login') {
            //用户首次登录，直接跳转到修改密码页面
            if(store.state.appSetting.isFirstLogin){
                if(to.name === "changePassword"){
                    next();
                }else {
                    next({path: '/user/changePassword'});
                }
                return;
            }
            next({path: '/'})
            NProgress.done()
        } else {
            if (!store.state.appSetting.logined) {
                sessionStorage.removeItem(JsConstant.CUR_APP_ID);
                store.dispatch('appSetting/GenerateRoutes').then((routers) => {
                    //用户首次登录，直接跳转到修改密码页面
                    if(store.state.appSetting.isFirstLogin){
                        next({path: '/user/changePassword'});
                    }
                    //把已获取到的路由菜单加入到路由表中
                    router.addRoutes(routers);
                    router.options.routes = [...constantRouterMap,...routers]
                    let redirect = decodeURIComponent(from.query.redirect || to.path);
                    let ary = router.options.routes;
                    let flag = false;
                    for(let idx in ary){
                        let obj = ary[idx];
                        flag = hasRouter(obj,obj.path,(item,url)=>{
                            if(url == redirect || (to.name && item.name == to.name)){
                                if(item.meta && item.meta.menuType == 'R'){
                                    localStorage.setItem("hideArea",true);
                                }else{
                                    localStorage.removeItem("hideArea");
                                }
                                return true;
                            }
                            return false;
                        })
                        if(flag){
                            break;
                        }
                    }
                    if(!flag){
                        MessageBox.show({message:I18Parse.getI18Val(componentLang,"noAuthGrant","没有权限访问!")});
                        return;
                    }
                    if(to.path ==='/'){
                        next({path:'/designApp'})
                    }else if (to.path === redirect) {
                        // hack方法 确保addRoutes已完成 ,set the replace: true so the navigation will not leave a history record
                        next({...to, replace: true})
                    } else {
                        // 跳转到目的路由
                        location.href=redirect;
                    }

                })
            } else {
                //用户首次登录，直接跳转到修改密码页面
                if(store.state.appSetting.isFirstLogin){
                    if(to.name === "changePassword"){
                        next();
                    }else {
                        next({path: '/user/changePassword'});
                    }
                }
                next();
            }
        }
    } else {
        let portal=process.env.VUE_APP_PORTAL;
        if (whiteList.includes(to.name) && (['login','qrcodeLogin','mobileCodeLogin'].includes(to.name) && portal != 'true')) {
            next();
            return;
        }
        if(portal != 'true') {
            next({path: '/user/login'});
            NProgress.done()
        }else {
            //1.先判断是否有state，如果没有证明第一次进入，则跳转到登录页，否则就是回调页
            let queryState = getQueryVariable('state');
            if (queryState) {
                let localState = sessionStorage.getItem("state");
                //判断state防止CSRF攻击
                if (localState !== queryState) {
                    let state = getState();
                    sessionStorage.setItem("state", state);
                    window.location = getAuthorizeUri(state,client_id,function(authorizeUri,data){
                        sessionStorage.setItem("visitUri", data.redirect_uri);
                        window.open(authorizeUri, '_self');
                    });
                } else {
                    //进入回调页面
                    //url获取code
                    let code = getQueryVariable('code');
                    const url = "/api-user/user/org/token/getTokenByCode" + "?code=" + code + '&clientId=' + client_id;
                    rxAjax.get(url).then(resp => {
                        TokenUtil.setToken(resp.access_token);
                        window.location = sessionStorage.getItem('visitUri');
                    }).catch((err) => {
                        console.log(err.response)
                    })
                }
            } else {
                let state = getState();
                sessionStorage.setItem("state", state);
                //构建调整url
                getAuthorizeUri(state,client_id,function(authorizeUri,data){
                    sessionStorage.setItem("visitUri", data.redirect_uri);
                    window.open(authorizeUri, '_self');
                });
            }
        }
    }
})

router.afterEach(() => {
    NProgress.done() // finish progress bar
    setTimeout(function () {
        store.state.appSetting.loading = false
    }, 300)
})

